<template>
  <div class="app-container">
    <div>
      <el-row :gutter="20">
        <el-col :span="24" :xs="24">
          <!-- 数据筛选表单 -->
          <el-form ref="queryForm" :model="queryParams" :inline="true">
            <!-- 数据筛选表单组件 -->
            <el-form-item :label="$t('clothes.clothesNumber')" prop="clothesNumber">
              <el-input
                v-model="queryParams.clothesNumber"
                :placeholder="$t('clothes.enterClothesNumber')"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item :label="$t('clothes.clothesName')" prop="clothesName">
              <el-input
                v-model="queryParams.clothesName"
                :placeholder="$t('clothes.enterClothesName')"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item :label="$t('clothes.category.category')" prop="categoryId">
              <el-select v-model="queryParams.categoryId" :placeholder="$t('clothes.selection')">
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.categoryId"
                  :label="item.categoryName"
                  :value="item.categoryId"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('clothes.search') }}</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('clothes.reset') }}</el-button>
              <el-button type="primary" icon="el-icon-plus" @click="handleAdd">{{ $t('clothes.addClothes') }}</el-button>
            </el-form-item>
          </el-form>
          <!-- 图片展示 -->
          <el-row>
            <el-col v-for="(product, i) in productList" :key="i" :span="6">
              <div>
                <product-image-information
                  :product-image="product"
                  @showDetails="showProductDetails(product)"
                  @update="update(product)"
                  @delete="deleteData(product)"
                />
              </div>
            </el-col>
          </el-row>
          <!-- 分页加载 -->
          <el-pagination
            :current-page="queryParams.pageNum"
            :page-sizes="[20, 50, 100]"
            :page-size="queryParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />

          <!-- 添加、修改服装对话框 -->
          <el-dialog :title="title" :visible.sync="open" width="1000px" :product="currentProduct" append-to-body>
            <el-form ref="form" :model="form">
              <el-row>
                <el-col :span="8">
                  <p class="upload-instruction">{{ $t('clothes.clothesImage') }}：</p>
                  <el-upload :action="uploadApi" list-type="picture-card" :auto-upload="true" :file-list="fileList">
                    <i slot="default" class="el-icon-plus" />
                    <div slot="file" slot-scope="{ file }">
                      <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                      <span class="el-upload-list__item-actions">
                        <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                          <i class="el-icon-zoom-in" />
                        </span>
                        <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
                          <i class="el-icon-download" />
                        </span>
                        <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                          <i class="el-icon-delete" />
                        </span>
                      </span>
                    </div>
                  </el-upload>
                </el-col>
                <el-col :span="16">
                  <el-form-item :label="$t('clothes.clothesNumber')" :label-width="formLabelWidth">
                    <el-input v-model="form.clothesNumber" autocomplete="off" />
                  </el-form-item>
                  <el-form-item :label="$t('clothes.clothesName')" :label-width="formLabelWidth">
                    <el-input v-model="form.clothesName" autocomplete="off" />
                  </el-form-item>
                  <el-form-item :label="$t('clothes.category.category')" prop="categoryId" :label-width="formLabelWidth">
                    <el-select v-model="form.categoryId" :placeholder="$t('clothes.selection')">
                      <el-option
                        v-for="item in categoryOptions"
                        :key="item.categoryId"
                        :label="item.categoryName"
                        :value="item.categoryId"
                      />
                    </el-select>
                  </el-form-item>
                  <el-tag style="margin-left: 80px;" type="success" effect="dark">{{ $t('clothes.discount') }}</el-tag>
                  <el-switch v-model="form.discountStatus" :active-value="true" :inactive-value="false" @change="setDiscount" />
                </el-col>
              </el-row>
            </el-form>
            <el-row>
              <el-col>
                <el-button size="small" icon="el-icon-edit" @click="insertClothesNormButton">{{ $t('clothes.addStock') }}</el-button>
                <el-table :data="clothesNormList" height="300">
                  <el-table-column sortable :label="$t('clothes.color')" prop="norm.color.colorName" />
                  <el-table-column sortable :label="$t('clothes.size')" prop="norm.size.sizeName" />
                  <el-table-column sortable :label="$t('clothes.price')" prop="price" />
                  <el-table-column :label="$t('clothes.stock')" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.quantity" :min="0" :max="9999" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    :label="$t('clothes.operation')"
                    align="center"
                    class-name="small-padding
"
                  >
                    <template slot-scope="scope">
                      <el-button size="small" type="text" icon="el-icon-edit" @click="updateClothesNorm(scope.row)">{{ $t('clothes.updateStock') }}</el-button>
                      <el-button size="small" type="text" icon="el-icon-delete" @click="delClothesNorm(scope.row)">{{ $t('clothes.del') }}</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
              <el-col />
            </el-row>

            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitForm">{{ $t('clothes.confirm') }}</el-button>
              <el-button @click="open = false">{{ $t('clothes.cancel') }}</el-button>
            </div>
          </el-dialog>

          <!-- 服装详情对话框 -->
          <el-col v-for="(product, i) in productList" :key="i" :span="4">
            <el-dialog
              :title="title"
              :visible.sync="detail"
              width="500px"
              append-to-body
              :product="currentProduct"
              @close="detail = false"
            >
              <el-form :model="form" class="product-form">
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="">
                      <!-- 使用 v-if 确保 currentProduct 和 currentProduct.url 都存在 -->
                      <el-image
                        v-if="currentProduct && currentProduct.url"
                        :src="currentProduct.url"
                        fit="contain"
                        width="100%"
                      />
                      <!-- 如果 currentProduct 或 currentProduct.src 不存在，可以显示一个占位符或加载指示器 -->
                      <div v-else>
                        <!-- 例如：加载中... 或 图片不可用 -->
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="16">
                    <el-form-item :label="$t('clothes.clothesNumber')" :label-width="formLabelWidth">
                      <el-input
                        v-if="currentProduct && currentProduct.clothesNumber"
                        v-model="currentProduct.clothesNumber"
                        disabled
                        autocomplete="off"
                      />
                    </el-form-item>
                    <el-form-item :label="$t('clothes.clothesName')" :label-width="formLabelWidth">
                      <el-input
                        v-if="currentProduct && currentProduct.clothesName"
                        v-model="currentProduct.clothesName"
                        disabled
                        autocomplete="off"
                      />
                    </el-form-item>
                    <el-form-item :label="$t('clothes.category.category')" :label-width="formLabelWidth">
                      <el-input
                        v-if="currentProduct && currentProduct.category.categoryName"
                        v-model="currentProduct.category.categoryName"
                        disabled
                        autocomplete="off"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <el-table :data="currentClothesNormList" height="400">
                <el-table-column :label="$t('clothes.color')" prop="norm.color.colorName" />
                <el-table-column :label="$t('clothes.size')" prop="norm.size.sizeName" />
                <el-table-column :label="$t('clothes.price')" prop="price" />
                <el-table-column :label="$t('clothes.stock')" prop="quantity" />
              </el-table>
            </el-dialog>
          </el-col>
        </el-col>
      </el-row>
    </div>
    <el-dialog :visible.sync="stockVis">
      <div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card>
              <span>{{ $t('clothes.color') }}</span>
              <el-form inline class="custom-form">
                <div class="checkbox-group">
                  <div class="checkbox-container">
                    <el-form-item v-for="color in colors" :key="color.id" class="custom-form-item">
                      <el-checkbox v-model="selectedColors" :label="color.id">{{ color.name }}</el-checkbox>
                    </el-form-item>
                  </div>
                  <el-form-item class="input-form-item">
                    <el-input v-model="newColor" :placeholder="$t('clothes.enterColor')" />
                    <el-button type="primary" @click="addNewColor">{{ $t('clothes.addColor') }}</el-button>
                  </el-form-item>
                </div>
              </el-form>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card>
              <span>{{ $t('clothes.size') }}</span>
              <el-form inline class="custom-form">
                <div class="checkbox-group">
                  <div class="checkbox-container">
                    <el-form-item v-for="size in sizes" :key="size.id" class="custom-form-item">
                      <el-checkbox v-model="selectedSizes" :label="size.id">{{ size.name }}</el-checkbox>
                    </el-form-item>
                  </div>
                  <el-form-item class="input-form-item">
                    <el-input v-model="newSize" :placeholder="$t('clothes.enterSize')" />
                    <el-button type="primary" @click="addNewSize">{{ $t('clothes.addSize') }}</el-button>
                  </el-form-item>
                </div>
              </el-form>
            </el-card>
          </el-col>
        </el-row>
        <!-- 新增库存 -->
        <el-table :data="skus" style="width: 100%">
          <el-table-column prop="colorName" sortable :label="$t('clothes.color')" />
          <el-table-column prop="sizeName" sortable :label="$t('clothes.size')" />
          <el-table-column :label="$t('clothes.price')">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.price" @change="updatePrice(scope.row.price)" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('clothes.stock')">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.quantity" @change="updateQuantity(scope.row.quantity)" />
            </template>
          </el-table-column>
        </el-table>
        <el-table :data="[batchRow]" style="width: 100%">
          <el-table-column :label="$t('clothes.price')">
            <template>
              <el-input-number v-model="batchPrice" style="margin-right: 50px;" @change="updateBatchPrice()" />
              <el-button type="text" @click="setBatchPrice()">{{ $t('clothes.batchSetPrice') }}</el-button>
            </template>
          </el-table-column>
          <el-table-column :label="$t('clothes.stock')">
            <template>
              <el-input-number v-model="batchQuantity" style="margin-right: 50px;" @change="updateBatchQuantity()" />
              <el-button type="text" @click="setBatchQuantity()">{{ $t('clothes.batchSetQuantity') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button @click="stockVis = false">{{ $t('clothes.cancel') }}</el-button>
          <el-button type="primary" @click="insertClothesNorm">{{ $t('clothes.confirm') }}</el-button>
        </span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ProductImageInformation from '@/components/ProductImageInformation.vue'
import { listClothesByPage, delClothes, addClothes, getClothesList, updateClothes, addColor, addSize } from '@/api/clothes'
import { getClothesNormList, delClothesNorm, addClothesNorm, updateClothesNorm } from '@/api/oss'
import { getColorList, getSizeList } from '@/api/sale'
import { getCategoryList } from '@/api/category'
export default {
  components: { ProductImageInformation },

  data() {
    return {
      updateVisiable: false,
      stockVis: false,
      colors: [],
      sizes: [],
      selectedColors: [],
      selectedSizes: [],
      skus: [],
      batchRow: { colorName: '批量设置', sizeName: '', price: '', quantity: '' },
    batchPrice: 0,
    batchQuantity: 0,
      newColor: '',
      newSize: '',
      uploadApi: process.env.VUE_APP_BASE_API + '/oss/upload',
      open: false, // 控制对话框的显示与隐藏
      fileList: [], // 用于存储上传组件的文件列表
      currentProduct: null,
      detail: false,
      loading: false,
      clothesList: [],
      categoryOptions: [],
      multiple: true,
      single: false,
      title: '',
      total: 0,
      ids: [],
      form: {
      },
      clothesNormList: [],
      currentClothesNormList: [],
      queryParams: {
        // 查询参数
        pageNum: 1,
        pageSize: 20,
        clothesName: null,
        clothesId: null,
        categoryId: null,
        clothesNorms: null
      },
      dialogFormVisible: false,
      showDetailsModal: false,
      formLabelWidth: '120px',
      productList: [],
      insertClothesNormForm: {}
    }
  },
  watch: {
    selectedColors: {
      handler() {
        this.updateSkus()
      },
      deep: true
    },
    selectedSizes: {
      handler() {
        this.updateSkus()
      },
      deep: true
    }
  },
  created() {
    this.getClothesList()
    this.getCategoryOptions()
    this.getNormData()
    this.getClothesNormList()
  },
  methods: {
    /** 表单初始化 */
    resetForm() {
      this.form = {
        clothesId: null,
        clothesName: null,
        categoryId: null,
        clothesNorms: null
      }
    },
    resetUpload() {
      // 重置上传组件的状态，包括清空文件列表
      this.fileList = []
    },
    // 获取衣服列表
    getClothesList() {
      this.loading = true
      listClothesByPage(this.queryParams).then((response) => {
        this.productList = response.data.list.map(product => {
          return { ...product }
        })
        this.total = response.data.total
        this.loading = false
      })
      // .then(this.$message.success('查询成功'))
      // .catch((error) => {
      //   console.error('没有该商品，请重新输入', error)
      // })
    },
    // 获取类别列表，绑定至类别筛选框
    getCategoryOptions() {
      getCategoryList({}).then((response) => {
        this.categoryOptions = response.data
      })
    },
    // 获取库存列表
    getClothesNormList() {
      const clothesNumber = this.form.clothesNumber
      getClothesNormList({ clothesNumber })
        .then((response) => {
          this.clothesNormList = response.data.filter(
            (item) => item.clothesNumber === clothesNumber
          )
        })
        .catch((error) => {
          console.error('获取库存列表失败：', error)
        })
    },
    /** 数据筛选搜索按钮 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getClothesList()
    },
    /** 数据筛选重置按钮 */
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.getClothesList()
    },
    /** 处理添加图片按钮 */
    handleAdd() {
      this.resetForm()
      this.clothesNormList = null
      this.open = true
      this.title = this.$t('clothes.addClothes')
      this.resetUpload() // 重置上传组件状态
      // if (this.currentProduct && Array.isArray(this.currentProduct.clothesNorms) && this.currentProduct.clothesNorms.length > 0) {
      //   this.currentProduct.clothesNorms[0].price = '' // 或者设置为null，或者您想要的任何默认值
      // }
    },
    /** 显示服装信息 */
    showProductDetails(product) {
      this.detail = true
      this.currentProduct = product
      const currentClothesNumber = this.currentProduct.clothesNumber
      getClothesNormList({ clothesNumber: currentClothesNumber })
        .then((response) => {
          this.currentClothesNormList = response.data
          this.title = '服装信息'
        })
        .catch((error) => {
          console.error('获取库存列表失败：', error)
        })
    },
    update(product) {
      this.updateVisiable = true
      this.open = true
      this.currentProduct = product
      console.log('currentProduct:', this.currentProduct)
      this.title = this.$t('clothes.updateClothes')
      // 将 currentProduct 的数据复制到 form 对象中
      this.form = { ...this.currentProduct }
      this.form.discountStatus = this.currentProduct.discountStatus === 'true'
      console.log('form:', this.form)
      this.resetUpload() // 重置上传组件状态
      this.getClothesNormList(product)
    },
    submitForm: function() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.clothesId != null) {
            // 如果存在 id 属性，则执行修改操作
            updateClothes(this.form).then((response) => {
              this.$message.success(response.msg)
              this.getClothesList()
              this.cancel()
            })
          } else {
            // 如果不存在 id 属性，则执行添加操作
            addClothes(this.form).then((response) => {
              this.$message.success(response.msg)
              this.getClothesList()
              this.cancel()
            })
          }
        }
      })
    },
    deleteDate(product) {
      this.title = this.$t('clothes.del')
      this.currentProduct = product
      const currentProductId = product.clothesId
      this.$confirm(
        '是否确认下架ID为"' + currentProductId + '"的服装?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          return delClothes({ clothesId: currentProductId })
        })
        .then(() => {
          this.getClothesList()
          this.$message.success('下架成功')
        })
        .catch(() => {
          this.$message.error('下架失败')
        })
    },
    insertClothesNormButton() {
      this.stockVis = true
      this.skus = null
      this.selectedColors = []
      this.selectedSizes = []
    },
    insertClothesNorm() {
      this.stockVis = false
      const skusData = this.skus.map(sku => {
        const colorId = this.colors.find(color => color.name === sku.colorName).id
        const sizeId = this.sizes.find(size => size.name === sku.sizeName).id
        const clothesNumber = this.form.clothesNumber
        return {
          clothesNumber,
          colorId,
          sizeId,
          price: sku.price,
          quantity: sku.quantity
        }
      })
      Promise.all(skusData.map(skuData => {
        return addClothesNorm(skuData).then(response => {
          console.log('库存增加成功', response)
          this.getClothesNormList(this.currentProduct)
          return response // 返回响应，以便在 Promise.all 完成时处理
        }).catch(error => {
          console.error('库存增加失败', error)
          throw error // 抛出错误，让 Promise.all 知道有操作失败
        })
      })).then(() => {
        // 所有库存增加操作完成后，重新获取库存列表
        this.getClothesNormList(this.currentProduct) // 假设 this.currentProduct 包含所需的 product 信息
      }).catch(() => {
        this.$message.error('增加库存时发生错误')
      })
    },
    delClothesNorm(row){
      const clothesNormId = row.clothesNormId
      this.$confirm('是否确认下架ID为"' + clothesNormId + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        return delClothesNorm({ clothesNormId })
      })
      .then(() => {
        this.getClothesNormList() // 刷新数据
        this.$message.success('下架成功')
      })
      .catch(() => {
    this.$message.error('下架失败')
})
    },
    updateClothesNorm(row){
      const clothesNormId = row.clothesNormId
      const clothesNumber = row.clothesNumber
      const normSn = row.normSn
      const price = row.price
      const quantity = row.quantity
      return updateClothesNorm({ clothesNormId, clothesNumber, normSn, price, quantity })
       .then(() => {
        this.getClothesNormList() // 刷新数据
        this.$message.success('更新库存成功')
      })
      .catch(() => {
    this.$message.error('更新失败')
})
    },
    getNormData() {
      // 假设getColorList是一个返回Promise的函数
      getColorList({}).then(response => {
        // 使用map来转换response.data为需要的格式
        this.colors = response.data.map(color => {
          return { id: color.colorId, name: color.colorName }
        })
      }).catch(error => {
        console.error('获取颜色列表异常:', error)
      })
      getSizeList({}).then(response => {
        this.sizes = response.data.map(size => {
          return { id: size.sizeId, name: size.sizeName }
        })
        console.log('sizes是', this.sizes)
      }).catch(error => {
        console.error('获取尺寸列表异常:', error)
      })
    },
    addNewColor() {
      addColor({ colorName: this.newColor }).then(response => {
        this.getNormData()
        this.newColor = null
      }).catch(error => {
        console.error('添加新颜色失败', error)
      })
    },
    addNewSize() {
      addSize({ sizeName: this.newSize }).then(response => {
        this.getNormData()
        this.newSize = null
      }).catch(error => {
        console.error('添加新尺寸失败', error)
      })
    },
    updateSkus() {
      this.skus = this.selectedColors
        .map(colorId => this.colors.find(color => color.id === colorId).name)
        .map(colorName =>
          this.selectedSizes.map(sizeId => {
            const sizeName = this.sizes.find(size => size.id === sizeId).name
            return { colorName, sizeName, price: 0, quantity: 0 }
          })
        ).flat()
    },
    updatePrice(price) {
    this.batchPrice = price
  },
  updateQuantity(quantity) {
    this.batchQuantity = quantity
  },
  setBatchPrice() {
    this.skus.forEach(sku => {
      sku.price = this.batchPrice
    })
  },
  setBatchQuantity() {
    this.skus.forEach(sku => {
      sku.quantity = this.batchQuantity
    })
  },
  updateBatchPrice() {
    this.skus.forEach(sku => {
      sku.price = this.batchPrice
    })
  },
  updateBatchQuantity() {
    this.skus.forEach(sku => {
      sku.quantity = this.batchQuantity
    })
  },
    setDiscount(val) {
      console.log(val)
    },
    /** 返回 **/
    cancel() {
      this.open = false
    },
    /** 处理分页 */
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getClothesList()
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getClothesList()
      console.log('pageNum=', this.queryParams.pageNum)
      console.log('val=', val)
    }
  }
}
</script>

<style scoped>
.custom-form {
  margin-bottom: 20px;
}

.checkbox-group {
  display: flex;
  flex-direction: column;
}

.checkbox-group h3 {
  margin-bottom: 10px;
}

.checkbox-container {
  display: flex;
  flex-wrap: wrap;
}

.custom-form-item {
  margin-right: 20px;
  margin-bottom: 10px;
}

.input-form-item {
  display: flex;
  align-items: center;
}

.input-form-item .el-input {
  width: 120px;
  margin-right: 10px;
}
</style>
